package cn.com.sparkle.paxos.addprocess;

import java.io.Serializable;
import java.util.LinkedList;

import org.apache.log4j.Logger;

import com.google.protobuf.ByteString;



//import cn.com.sparkle.paxos.client.net.message.AddRequest;
//import cn.com.sparkle.paxos.net.message.MessagePackage;
import cn.com.sparkle.paxos.iomodel.protobuffmessage.PaxosMessages.AddRequest;
import cn.com.sparkle.paxos.iomodel.protobuffmessage.PaxosMessages.AddResponse;
import cn.com.sparkle.paxos.iomodel.protobuffmessage.PaxosMessages.CommandResponse;
import cn.com.sparkle.paxos.iomodel.protobuffmessage.PaxosMessages.MessagePackage;
import cn.com.sparkle.paxos.net.factory.NetCloseException;
import cn.com.sparkle.paxos.net.factory.PaxosSession;

public class AddRequestPackage {
	private final static Logger logger = Logger
			.getLogger(AddRequestPackage.class);
	public LinkedList<ByteString> valueList = new LinkedList<ByteString>();
	private PaxosSession session;
	private long valueByteSize = 0;

	private boolean isManageCommand = false;

	private LinkedList<Long> messagePackageId = new LinkedList<Long>();

	public AddRequestPackage(MessagePackage mp, PaxosSession session) {
		super();
		addRequest(mp);
		isManageCommand = (mp.getAddRequest()).getIsManagerCommand();
		this.session = session;
	}

	public void addRequest(MessagePackage mp) {
		if (isManageCommand) {
			throw new RuntimeException(
					"admin package is not permitted to append a request");
		}
		messagePackageId.addLast(mp.getId());
		AddRequest request = mp.getAddRequest();
		this.valueByteSize += request.getValue().size();

		valueList.addLast(request.getValue());
	}

	public void response(AddResponse response) {
		long responseId = messagePackageId.removeFirst();
		MessagePackage responseMp = MessagePackage.newBuilder().setIsLast(true)
				.setId(responseId).setAddResponse(response).build();
		// MessagePackage responseMp = new MessagePackage(responseId, response,
		// true);
		try {
			session.write(responseMp);
		} catch (NetCloseException e) {
		}
		// logger.debug("response id:" + responseId + "  waitResponseSize:"
		// + messagePackageId.size());
	}

	public void response(CommandResponse response) {
		long responseId = messagePackageId.removeFirst();
		MessagePackage responseMp = MessagePackage.newBuilder().setIsLast(true)
				.setId(responseId).setCommandResponse(response).build();
		try {
			session.write(responseMp);
		} catch (NetCloseException e) {
		}
	}

	public long nextWaitResponsePackageId() {
		return messagePackageId.removeFirst();
	}

	public void closeConnection() {
		session.closeSession();
	}

	public long getValueByteSize() {
		return valueByteSize;
	}

	public PaxosSession getSession() {
		return session;
	}

	public boolean isManageCommand() {
		return isManageCommand;
	}
}